#include <iostream>
using namespace std;

/*
    throw 抛出异常之后,会在当前的函数中查找匹配的catch块，
    如果没有找到，则向上抛出，直到找到[匹配的]catch块，或者抛出异常没有被处理，导致程序崩溃。
*/
int myDiv(int val1, int val2)
{
    if (val2 == 0)
    {
        /*抛异常*/
        throw "除数不能为0";
    }
    return val1 / val2;
}

/*实现异常基类*/
class myException
{
public:
    virtual string what() = 0;
};

/*触发异常*/
class DivException : public myException
{
public:
    string what()
    {
        return "除数不能为0";
    }

private:
    string m_msg;
};

int myDivide(int val1, int val2)
{
    if (val2 == 0)
    {
        /*抛异常*/
        throw DivException();
    }
    return val1 / val2;
}

// int myMulti(int val1, int val2)
// {
//     if (val1 > 100 || val2 > 100)
//     {
//         throw MulE
//     }

//     return val1 * val2;
// }

int main()
{
#if 0
    /*异常没有被处理会导致程序崩溃，所以需要捕获异常*/
    try
    {
        cout << myDiv(10, 0) << endl;
    }
    catch (const char *exception)
    {
        cout << "捕获到异常" << endl;
        cout << "exception:" << exception << endl;
    }

#endif

#if 0
    try
    {

        int res = myDivide(100, 0);
        cout << "res:" << res << endl;
    }
    catch (const exception &e)
    {
        std::cerr << e.what() << '\n';
    }
#endif

#if 1
    /*模拟内存不足*/
    try
    {
        int size = 100000000;
        for (int i = 0; i < size; i++)
        {
            int *p = new int[100000000];
        }
    }
    catch (const exception &e)
    {
        cout << "捕获到异常" << endl;
        cout << "exception:" << e.what() << endl;
    }
    while (1)
    {
        sleep(1);
    }
    

#endif

    return 0;
}